<script setup>
import _ from 'lodash';
// import {} from "../../../common/common";
import {DFT_ICONS} from "@jzl/icons";
import {useCommonStore} from "@jzl/stores";
import {computed, onMounted, reactive, ref, toRefs, watch} from "vue";
import {api} from "@jzl/api";
import { $menuUtils, $utils } from "@jzl/utils";
import { $WinForms } from '@jzl/comps';
import { $WinPages, $WinComps } from '@jzl/comps-mg';

const DEFAULT_FORM = {
  content_type: 'NORMAL',
  content_name: "",
  content_code: "",
  content_desc: "",
  icon: { icon: '', image: '', color: ''},
  form_id: -1,
  flow_id: -1,
  arg0: '',
  is_default_menu: 0,
  is_white_menu: 0,

  form: {form_id: '', form_name: ''},
  view: {form_view_id: '', view_name: ''},
  page_id: null,
  page: {page_id: '', page_name: ''},
  rule: {openType: "_self", framework: 'inherit', frameApp: '', query: {}},

  comp_id: null,
  comp: {}
}

const emit = defineEmits(['success', 'cancel'])
const props = defineProps({
  actionType: {
    type: String,
    default: 'view'
  }, // actionType: 'view',     // createGroup | createMenu | edit | view
  currentData: Object,
  parentGroupId: null,
  tty: null,
  menutree: null,
  appId: null
})

const {
  loading,
  groups,
  form,
  groupTreeData,
  groupTreeSetting,
  expandedKeys
} = toRefs(reactive(({
  loading: false,
  groups: [],

  form: _.cloneDeep(DEFAULT_FORM),

  groupTreeData: [],
  groupTreeSetting: {
    children: 'subs',
    label: 'name',
  },
  expandedKeys: [],
})))

const appPopoverRef = ref(null);
const appPopoverShow = ref(false)
const appPopoverTrigger = ref(null)

const targetCompLabel = computed(() => {
  if (!form.value.comp) return '';

  let names = [];

  if (form.value.comp.name) {
    names.push(form.value.comp.name);
  }

  if (form.value.comp.comp_lib) {
    names.push(form.value.comp.comp_lib);
  }

  if (form.value.comp.comp_name) {
    names.push(form.value.comp.comp_name);
  }

  return names.join(' | ');
})

const targetAppLabel = computed(() => {
  if (!form.value.rule) return '';

  let names = [];
  if (form.value.rule.faName) {
    names.push(form.value.rule.faName);
  }

  if (form.value.rule.frameApp) {
    names.push(form.value.rule.frameApp);
  }

  return names.join(' | ');
})

onMounted(() => {
  init()
})

watch(() => [props.actionType, props.currentData], () => {
  init()
}, {deep: true})

const viewLabel = (view) => {
  return view?.view_name || '默认';
}

const init = () => {
  let iForm = null;

  if (props.actionType === 'createMenu') {
    iForm = _.defaults({
      project_id: useCommonStore().project?.project_id,
      content_group_id: _.get(props.currentData, 'group_id', props.appId) || props.appId || -1,
      content_type: 'NORMAL',
      content_name: "",
      content_code: $utils.getNanoid(10),
      content_desc: "",
      tty: props.tty,
      form_id: -1,
      is_default_menu: 0,
      form: null,
      view: null,
      flow: null,
      page_id: null,
      comp_id: null,
      page: null,
      comp: null
    }, DEFAULT_FORM);
  } else {
    iForm = _.cloneDeep(props.currentData);

    if (!iForm.icon) {
      iForm.icon = { icon: '', color: '', image: '' };
    } else if (_.isString(iForm.icon)) {
      iForm.icon = { icon: iForm.icon, color: '', image: '' };
    }

    if(!iForm.icon.icon && iForm.icon.iconfont) {
      iForm.icon.icon = iForm.icon.iconfont;
    }

    if (!iForm.rule) {
      iForm.rule = {openType: "_self", query: {}};
    }
  }

  form.value = iForm;
  initMenuGroup();
}

const initMenuGroup = async () => {
  let groups = await api.menu.getGroupTree(1);

  groups = _.concat([{
    group_code: "",
    name: "默认",
    remark: "",
    icon: { color: "#409EFF", icon: "fa fa-tint-slash" },
    tid: ""
  }, {
    group_code: "_nh",
    name: "无页头",
    remark: "",
    icon: {color: "#409EFF", icon: "fa fa-tint-slash" },
    tid: "_web"
  }, {
    group_code: "_nm",
    name: "无菜单",
    remark: "",
    icon: {color: "#409EFF", icon: "fa fa-eye-slash" },
    tid: "_web"
  }, {
    group_code: "_h5",
    name: "H5菜单",
    remark: "",
    icon: {color: "#409EFF", icon: "fa fa-mobile-alt" },
    tid: "_h5"
  }, {
    group_code: "_web",
    name: "WEB菜单",
    remark: "",
    icon: {color: "#409EFF", icon: "fa fa-tv" },
    tid: "_web"
  }, {
    group_code: "_app",
    name: "当前应用菜单",
    remark: "目标页面所属应用菜单",
    icon: {color: "#409EFF", icon: "fa fa-app-store" },
    tid: "_app"
  }], groups);

  groupTreeData.value = groups;
  expandedKeys.value = _.map(groups, "tid")
}

const handleSubmitCreateMenu = async () => {
  let data = _.cloneDeep(form.value);
  let id = _.get(data, 'content_id');
  let ret = null;

  // 系统菜单，编码不能为空
  /*if(data.content_type === 'CUSTOMNAME') {
      if(!data.content_code) {
          return this.$message('系统编码不能为空！');
      }
  } else */
  if (!data.content_code) {
    data.content_code = $utils.getNanoid(10)
  }

  if (id) {
    ret = await api.menu.updateMenu(id, data);
  } else {
    ret = await api.menu.createMenu(data);
  }

  if (!ret) return;

  let tid = _.get(form.value, 'tid') || `c_${_.get(ret, 'content_id')}`;

  loading.value = false;
  $jui.toast('操作成功！');

  emit('success', tid);
}

const handleShowFormSelectWin = () => {
  $WinForms({
    type: 'view',
    onConfirm: (info) => {
      let selectedForm = _.get(info, 'form');
      let selectedView = _.get(info, 'view');
      if (!selectedForm?.form_id) return;

      form.value.form_id = selectedForm.form_id;
      form.value.form = selectedForm;
      form.value.view = selectedView;
      form.value.view_id = _.get(selectedView, 'form_view_id', -1);
      // this.$set(form.value, 'form', form);
      // this.$set(form.value, 'view', view);
      // console.log(form.value.form, form.value.view);
    }
  });
}

const handleShowPageSelectWin = () => {
  let gid = null;

  if (props.actionType === 'createMenu') {
    gid = _.get(props.currentData, 'group_id', props.appId) || -1;
  } else {
    gid = _.get(props.currentData, 'content_group_id', -1);
  }

  let app = getCurrentApp(gid);

  $WinPages({
    defaultAppId: _.get(app, 'group_id', -1),
    onConfirm: (page) => {
      let pageId = _.get(page, 'page_id');

      if (!pageId) return;

      form.value.page_id = pageId;
      form.value.page = page;
      // $set(form.value, 'page', page);
    }
  });
}

const handleShowCompSelectWin = () => {
  $WinComps({
    onConfirm: (comp) => {
      // console.log(comp)
      if (!comp || !comp.comp_name) return;
      form.value.comp_id = comp.id;
      form.value.comp = comp;
      // this.$set(form.value, 'comp', comp);
    },
    onCancel() {
    }
  });
}

const handleShowPagePreview = (page) => {
  $WinPagePreview({
    page: page,
    pageId: _.get(page, 'page_id'),
    pageCode: _.get(page, 'page_code')
  });
}

const handleCancelEdit = () => {
  emit('cancel');
}

const getCurrentApp = (id) => {
  let paths = $utils.getTreePath(id, props.menutree, "group_id", 'subs', true);

  if (paths && paths.length) {
    for (let i = 0; i < paths.length; i++) {
      let p = paths[i];

      if (p && p.type === 2) return p;
    }
  }

  return null;
}

const handleSelectFrameApp = (data) => {
  let code = _.get(data, 'group_code');
  let name = _.get(data, 'group_name') || _.get(data, 'name');

  if (!code && code !== "") return;

  // emit(form.value.rule, "frameApp", code);
  // emit(form.value.rule, "faName", name);

  form.value.rule.frameApp = code;
  form.value.rule.faName = name;

  appPopoverShow.value = true;
  // appPopoverTrigger.value =
  // this.$refs.appPopoverRef.showPopper = false;
}
</script>

<template>
  <el-form ref="formRef" label-width="100px">
    <el-form-item label="菜单名称">
      <el-input
        v-model="form.content_name"
        placeholder="名称，如：产品"
        :disabled="actionType === 'view'"
      ></el-input>
    </el-form-item>
    <el-form-item label="菜单编码">
      <el-input
        v-model="form.content_code"
        placeholder="编码，如：PRODUCT_CAT"
        :disabled="actionType === 'view' || actionType === 'edit'"
      ></el-input>
    </el-form-item>
    <el-form-item label="">
      <el-checkbox
        v-model="form.is_default_menu"
        :true-label="1"
        :false-label="0"
        :disabled="actionType === 'view'"
      >默认菜单
      </el-checkbox>
      <el-checkbox
        v-model="form.is_white_menu"
        :true-label="1"
        :false-label="0"
        :disabled="actionType === 'view'"
      >白名单（仅菜单）
      </el-checkbox>
      <el-checkbox
        v-model="form.is_white_menu"
        :true-label="2"
        :false-label="0"
        :disabled="actionType === 'view'"
      >白名单（菜单&数据）
      </el-checkbox>
    </el-form-item>
    <el-form-item label="菜单图标">
      <div class="icons flex items-center">
        <IconPicker
          v-model="form.icon.icon"
          :is-view="actionType === 'view'"
          class="mr-2"
        />
        <ElColorPicker
          v-model="form.icon.color"
          :disabled="actionType === 'view'"
        />
        <!--<file-picker v-model="form.icon.image" theme="mini" :is-view="actionType == 'view'"></file-picker>-->
      </div>
      <!--<el-radio-group v-model="form.is_default_menu" :disabled="actionType == 'view'">
          <el-radio :label="0">不是</el-radio>
          <el-radio :label="1">是</el-radio>
      </el-radio-group> 是否默认

      <el-radio-group v-model="form.is_white_menu" :disabled="actionType == 'view'">
          <el-radio :label="0">不是</el-radio>
          <el-radio :label="1">是</el-radio>
      </el-radio-group> 是否白名单-->
    </el-form-item>
    <el-form-item label="菜单类型">
      <!-- 暂时放开，应该默认菜单不能修改类型 -->
      <el-radio-group
        v-model="form.content_type"
        :disabled="actionType === 'view'"><!-- || actionType == 'edit' -->
        <el-radio label="NORMAL">表单列表</el-radio>
        <!--<el-radio label="FORMADD" v-tippy="{ arrow: true }" content="表单数据新增的快捷方式">表单录入（新增数据）</el-radio>-->
        <!--<el-radio label="WORKFLOW">流程类</el-radio>-->
        <el-radio label="JZLPAGE">页面</el-radio>
        <el-radio label="COMP">组件页面</el-radio>
        <el-radio label="DATAMENU" v-tippy content="表单数据作为菜单" disabled>数据类</el-radio>
        <!--<el-radio label="CUSTOMNAME">系统功能</el-radio>-->
        <el-radio label="CUSTOMPATH">扩展/外链</el-radio>
      </el-radio-group>
      <!--<el-select v-model="form.content_type" placeholder="请选择菜单类型" :disabled="actionType == 'view'">
          <el-option label="通用" value="NORMAL"></el-option>
          <el-option label="内路由" value="CUSTOMNAME"></el-option>
          <el-option label="外链" value="CUSTOMPATH"></el-option>
      </el-select>-->
    </el-form-item>
    <el-form-item label="表单" v-if="form.content_type === 'NORMAL' || form.content_type === 'DATAMENU'">
      <template v-if="actionType !== 'view'">
        <el-tag
          v-if="form.form && form.form.form_id"
          class="mr-2"
        >
          {{ form.form.form_name }}
          <JIcon :icon="DFT_ICONS.braceLeft"/>
          {{ viewLabel(form.view) }}
          <JIcon :icon="DFT_ICONS.braceRight"/>
        </el-tag>
        <el-button
          type="primary"
          @click="handleShowFormSelectWin"
          size="small"
        >选择表单</el-button>
      </template>
      <template v-else-if="form.form">
        <el-tag>
          {{ form.form.form_name }}
          <JIcon :icon="DFT_ICONS.braceLeft"/>
          {{ viewLabel(form.view) }}
          <JIcon :icon="DFT_ICONS.braceRight"/>
        </el-tag>
      </template>
    </el-form-item>
    <el-form-item
      label="页面"
      v-else-if="form.content_type === 'JZLPAGE'">
      <el-tag
        v-if="form.page && form.page.page_id"
        @click="handleShowPagePreview(form.page)"
        class="cursor-pointer mr-2"
      >{{ form.page.page_name }}</el-tag>
      <template v-if="actionType !== 'view'">
        <el-button type="primary" @click="handleShowPageSelectWin">选择页面</el-button>
      </template>
    </el-form-item>
    <el-form-item label="组件" v-else-if="form.content_type === 'COMP'">
      <el-tag v-if="targetCompLabel" class="link-view-name mr-2"> {{ targetCompLabel }}</el-tag>
      <el-button type="primary" @click="handleShowCompSelectWin" size="mini"> 选择组件</el-button>
    </el-form-item>
    <!--<el-form-item label="流程" v-else-if="form.content_type == 'WORKFLOW'">
        <template v-if="actionType == 'createMenu'">
            <el-tag v-if="form.flow && form.flow.flow_id" size="medium" style="margin-right: 10px;">{{form.flow.flow_name}}</el-tag>
            <el-button type="primary" @click="handleShowFlowSelectWin">选择流程</el-button>
        </template>
        <template v-else-if="form.flow">
            <el-tag size="medium">{{form.flow.flow_name}}</el-tag>
        </template>
    </el-form-item>-->
    <el-form-item label="链接" v-else-if="form.content_type === 'CUSTOMPATH'">
      <el-input v-model="form.arg0" :disabled="actionType === 'view'"></el-input>
    </el-form-item>
    <el-form-item label="路由" v-else-if="form.content_type === 'CUSTOMNAME'">
      <el-input
        v-model="form.arg0"
        placeholder="系统路由的路径，如：basic/role"
        :disabled="actionType === 'view' || (actionType === 'edit' && form.content_type === 'CUSTOMNAME')"
      />
    </el-form-item>

    <el-form-item label="描述">
      <el-input type="textarea" :rows="2" v-model="form.content_desc" :disabled="actionType === 'view'"></el-input>
    </el-form-item>
    <el-form-item label="高级规则">
      <el-form size="mini" label-position="top" class="menu-rule-setting">
        <el-form-item label="打开方式" class="mb-1">
          <el-radio-group v-model="form.rule.openType" :disabled="actionType === 'view'">
            <el-radio-button label="_blank" v-tippy content="新窗口（_blank）">新窗口</el-radio-button>
            <el-radio-button label="_self" v-tippy content="本窗口（_self）">本窗口</el-radio-button>
            <el-radio-button label="_win" v-tippy content="弹窗（_win）">弹窗</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="主框架" class="mb-1">
          <el-select
            v-model="form.rule.framework"
            allow-create
            filterable
            default-first-option
            popper-class="select-vt"
          >
            <el-option value="" label="自动">
              <span class="sop-label">自动</span>
              <span class="sop-tip">按页面类型匹配</span>
            </el-option>
            <el-option value="inherit" label="当前一致">
              <span class="sop-label">当前一致</span>
              <span class="sop-tip">与来源页面一致</span>
            </el-option>
            <el-option value="/apps/jwsystem" label="管理框架">
              <span class="sop-label">管理框架</span>
              <span class="sop-tip">/apps/jwsystem</span>
            </el-option>
            <el-option value="/apps/jwpage" label="Web框架">
              <span class="sop-label">Web框架</span>
              <span class="sop-tip">/apps/jwpage</span>
            </el-option>
            <el-option value="/apps/jwh5" label="H5框架">
              <span class="sop-label">H5框架</span>
              <span class="sop-tip">/apps/jwh5</span>
            </el-option>
          </el-select>
          <span class="tip-txt ml-2">主框架页面，可自定义输入</span>
        </el-form-item>
        <el-form-item label="主菜单">
          <!--<select-tree :data="groupTreeData" :props="groupTreeSetting"></select-tree>-->
          <el-tag
            v-if="targetAppLabel"
            class="link-view-name mr-2"> {{ targetAppLabel }}
          </el-tag>

          <el-popover
            v-model:visible="appPopoverShow"
            popper-class="select-tree-popover"
            ref="appPopoverRef"
            placement="bottom-start"
            width="auto"
            trigger="click"
          >
            <el-tree
              ref="menutreeRef"
              class="menu-custom-tree"
              :data="groupTreeData"
              node-key="tid"
              :highlight-current="true"
              :expand-on-click-node="true"
              :default-expanded-keys="expandedKeys"
              :props="groupTreeSetting"
            >
              <template #default="{ node, data }">
                <span class="menu-custom-tree-node menu-icon-node">
                  <span
                    class="menu-custom-icon"
                    :class="{ 'is-app': $menuUtils.isApp(data), 'is-empty': $menuUtils.isGroup(data) }"
                    :style="$menuUtils.getIconStyle(data)"
                  >
                      <JIcon v-if="data?.loading" :icon="DFT_ICONS.loadingSpinner" />
                      <img v-else-if="$menuUtils.isGroup(data)" :src="$menuUtils.getIconDefault(data)"/>
                      <img v-else-if="$menuUtils.getIconImg(data)" :src="$menuUtils.getIconImg(data)"/>
                    <!--<i v-else-if="getIconFont(data)" :class="getIconFont(data)"></i>-->
                      <template v-else-if="$menuUtils.getIconFont(data)">
                          <JIcon :icon="$menuUtils.getIconFont(data)" />
                      </template>
                      <img v-else :src="$menuUtils.getIconDefault(data)"/>
                  </span>
                  <span class="menu-node-name" v-text="data?.name"></span>
                  <!--<i v-if="isApp(data)" class="app-icon fa fa-app-store" v-tippy content="应用"></i>
                  <i v-if="isWhite(data)" class="app-icon fa fa-weebly" v-tippy content="白名单菜单"></i>-->
                  <!--<i class="el-icon-arrow-up btn-up" @click.stop="handleMenuUp(data)"></i>
                  <i class="el-icon-arrow-down btn-down" @click.stop="handleMenuDown(data)"></i>-->
                  <el-button
                    v-if="data.type !== 1 || data.parent_id > 0"
                    type="text"
                    size="mini"
                    @click.stop="handleSelectFrameApp(data)"
                  >选择</el-button>
              </span>
              </template>
            </el-tree>
            <template #reference>
              <el-button type="primary" size="small"> 选择应用/菜单组</el-button>
            </template>
          </el-popover>
          <span class="tip-txt ml-2">主框架显示的应用菜单</span>
        </el-form-item>
        <el-form-item label="链接参数">
          <LinkQuery
            v-model="form.rule.query"
            :prop-form-id="form.form_id"
          />
        </el-form-item>
      </el-form>
    </el-form-item>
    <el-form-item
      label=""
      v-if="actionType !== 'view'">
      <el-button
        size="default"
        type="primary"
        @click="handleSubmitCreateMenu()"> 提交
      </el-button>
      <el-button
        size="default"
        @click="handleCancelEdit()"> 取消
      </el-button>
    </el-form-item>
  </el-form>
</template>

<style scoped lang="scss">
.menu-icon-node {
  padding-right: 5px;

  .menu-node-name {
    flex: 1;
  }

  > .el-button {
    opacity: 0;
    float: right;
    margin-left: 20px;
  }

  &:hover {
    > .el-button {
      opacity: 1;
    }
  }
}
</style>
